# -*- coding: utf-8 -*-
import simplejson, base64
import logging
from openerp import http
from openerp.http import request
_logger = logging.getLogger(__name__)

'''
#控件使用说明
--model字段设置
--8.0版本老api
class demo(osv.osv):

    def _data_get(self, cr, uid, ids, name, arg, context=None):
        if context is None:
            context = {}
        datas = []
        att = self.pool.get('ir.attachment')
        attIds = att.search(cr, uid, [('res_model','=',self._name),('res_id','=',ids[0])])
        attObjs = att.browse(cr, uid, attIds)
        for i in attObjs:
            if i.file_type_icon!='webimage':
                html = """<div class='oe_attachment oe_ff' data-id="%(attId)s"><a href='/mail/download_attachment?model=%(parentModel)s&id=%(parendId)s&method=download_attachment&attachment_id=%(attId)s' target='_blank'>
                        <img src='/mail/static/src/img/mimetypes/%(attIcon)s.png' />
                        <div class='oe_name' style='word-break: break-all;'>%(filename)s</div>
                    </a></div>""" % {
                                'parentModel':self._name,
                                'parendId':ids[0],
                                'attId':i.id,
                                'attIcon':(i.file_type_icon or 'unknown'),
                                'filename':i.name
                            }
            else:
                html = """<div class='oe_attachment oe_ff oe_preview' data-id="%(attId)s"><a href='/mail/download_attachment?model=%(parentModel)s&id=%(parendId)s&method=download_attachment&attachment_id=%(attId)s' target='_blank'>
                        <img src='/web/binary/image?model=ir.attachment&field=datas&id=%(attId)s&resize=100%%252C80' />
                        <div class='oe_name' style='word-break: break-all;'>%(filename)s</div>
                        </a></div>""" % {
                                'parentModel':self._name,
                                'parendId':ids[0],
                                'attId':i.id,
                                'filename':i.name
                            }
            datas.append({
                'id':i.id,
                'file_type_icon':i.file_type_icon,
                'datas_fname':i.datas_fname,
                'data':att._file_read(cr, uid, i.store_fname),
                'html':html
            })
        return {ids[0]:datas}

    def _data_set(self, cr, uid, id, name, value, arg, context=None):
        return True

    _columns = {
        'datas': fields.function(_data_get, fnct_inv=_data_set, string='测试附件', type="binary", nodrop=True),
    }

8.0版本新api
from openerp import models, fields

class demo(models.Model):

    _inherit = 'demo'


    datas = fields.Binary(compute='_data_get', inverse='_inverse_display_name',  string='测试附件')

    @api.one
    def _data_get(self):
        context = self.env.context
        if context is None:
            context = {}
        datas = []
        att = self.env['ir.attachment']
        attObjs = att.search([('res_model','=',self._name),('res_id','=',self.id)])
        for i in attObjs:
            if i.file_type_icon!='webimage':
                html = """<div class='oe_attachment oe_ff' data-id="%(attId)s"><a href='/mail/download_attachment?model=%(parentModel)s&id=%(parendId)s&method=download_attachment&attachment_id=%(attId)s' target='_blank'>
                        <img src='/mail/static/src/img/mimetypes/%(attIcon)s.png' />
                        <div class='oe_name' style='word-break: break-all;'>%(filename)s</div>
                    </a></div>""" % {
                                'parentModel':self._name,
                                'parendId':self.id,
                                'attId':i.id,
                                'attIcon':(i.file_type_icon or 'unknown'),
                                'filename':i.name
                            }
            else:
                html = """<div class='oe_attachment oe_ff oe_preview' data-id="%(attId)s"><a href='/mail/download_attachment?model=%(parentModel)s&id=%(parendId)s&method=download_attachment&attachment_id=%(attId)s' target='_blank'>
                        <img src='/web/binary/image?model=ir.attachment&field=datas&id=%(attId)s&resize=100%%252C80' />
                        <div class='oe_name' style='word-break: break-all;'>%(filename)s</div>
                        </a></div>""" % {
                                'parentModel':self._name,
                                'parendId':self.id,
                                'attId':i.id,
                                'filename':i.name
                            }
            datas.append({
                'id':i.id,
                'file_type_icon':i.file_type_icon,
                'datas_fname':i.datas_fname,
                'data':att._file_read(i.store_fname),
                'html':html
            })
        self.datas = datas

    @api.one
    def _inverse_display_name(self):
        pass




xml控件使用说明
<field name="datas" widget="ff_file_widget"/>
默认接受任何文件；如果需要限制上传文件类型，请设置属性limittype,例：
<field name="datas" widget="ff_file_widget" limittype="text"/>
多种文件以英文逗号隔开，例：limittype="txt,pdf,jpg"
文件类型限制只是比较文件的后缀名，无法过滤更改后缀名引起的误判
'''

class attachment_widget(http.Controller):
    @http.route('/attachment_widget/addFile/', auth='user')
    def addFile(self, **kw):
        ufile = kw.get('newfile')
        modelName = kw.get('model')
        id = int(kw.get('id'))
        Model = request.session.model('ir.attachment')
        try:
            attachment_id = Model.create({
                'name': ufile.filename,
                'datas': base64.encodestring(ufile.read()),
                'datas_fname': ufile.filename,
                'res_model':modelName,
                'res_id': id
            }, request.context)
        except:
            return simplejson.dumps({ "state":0, "data": "" })
        else:
            att = Model.browse(attachment_id)
            data = {
                'file_type_icon':att.file_type_icon,
                'parentModel':modelName,
                'parendId':id,
                'attId':att.id,
                'attIcon':(att.file_type_icon or 'unknown'),
                'filename':att.name
            }
            return simplejson.dumps({ "state":1,"data": data })
